package com.blog.blog.controller;

import com.blog.blog.common.ApiBaseResponse;
import com.blog.blog.service.BackupService;
import com.blog.blog.util.annotations.RequirePerm;
import com.blog.blog.vo.OssFileVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 备份管理控制器
 */
@Tag(name = "备份管理", description = "数据备份和恢复管理")
@RestController
@RequestMapping("/api/admin/backup")
@RequiredArgsConstructor
public class AdminBackupController {
    
    private final BackupService backupService;
    
    @Operation(summary = "执行数据库备份")
    @PostMapping("/database")
    @RequirePerm({"system:backup"})
    public ApiBaseResponse<Map<String, Object>> backupDatabase() {
        OssFileVO backup = backupService.backupDatabase();
        Map<String, Object> result = new HashMap<>();
        if (backup != null) {
            result.put("success", true);
            result.put("ossKey", backup.getKey());
            result.put("url", backup.getUrl());
            result.put("size", backup.getSize());
            result.put("message", "数据库备份成功，已上传到OSS");
        } else {
            result.put("success", false);
            result.put("message", "数据库备份失败");
        }
        return ApiBaseResponse.success(result);
    }
    
    @Operation(summary = "执行文件备份")
    @PostMapping("/files")
    @RequirePerm({"system:backup"})
    public ApiBaseResponse<Map<String, Object>> backupFiles() {
        OssFileVO backup = backupService.backupFiles();
        Map<String, Object> result = new HashMap<>();
        if (backup != null) {
            result.put("success", true);
            result.put("ossKey", backup.getKey());
            result.put("url", backup.getUrl());
            result.put("size", backup.getSize());
            result.put("message", "文件备份成功，已上传到OSS");
        } else {
            result.put("success", false);
            result.put("message", "文件备份失败");
        }
        return ApiBaseResponse.success(result);
    }
    
    @Operation(summary = "执行完整备份")
    @PostMapping("/full")
    @RequirePerm({"system:backup"})
    public ApiBaseResponse<Map<String, Object>> fullBackup() {
        OssFileVO backup = backupService.fullBackup();
        Map<String, Object> result = new HashMap<>();
        if (backup != null) {
            result.put("success", true);
            result.put("ossKey", backup.getKey());
            result.put("url", backup.getUrl());
            result.put("size", backup.getSize());
            result.put("message", "完整备份成功，已上传到OSS");
        } else {
            result.put("success", false);
            result.put("message", "完整备份失败");
        }
        return ApiBaseResponse.success(result);
    }
    
    @Operation(summary = "获取OSS备份文件列表")
    @GetMapping("/list")
    @RequirePerm({"system:backup"})
    public ApiBaseResponse<List<Map<String, Object>>> listBackups() {
        try {
            List<OssFileVO> backups = backupService.listBackupFiles();
            
            List<Map<String, Object>> result = backups.stream()
                .map(backup -> {
                    Map<String, Object> item = new HashMap<>();
                    item.put("ossKey", backup.getKey());
                    item.put("url", backup.getUrl());
                    item.put("size", backup.getSize());
                    item.put("lastModified", backup.getLastModified());
                    item.put("type", getBackupType(backup.getKey()));
                    item.put("fileName", extractFileName(backup.getKey()));
                    return item;
                })
                .sorted((a, b) -> {
                    // 按最后修改时间倒序排列
                    if (a.get("lastModified") != null && b.get("lastModified") != null) {
                        return ((java.util.Date) b.get("lastModified")).compareTo((java.util.Date) a.get("lastModified"));
                    }
                    return 0;
                })
                .toList();
                
            return ApiBaseResponse.success(result);
            
        } catch (Exception e) {
            return ApiBaseResponse.error(500, "获取备份文件列表失败: " + e.getMessage());
        }
    }
    
    @Operation(summary = "恢复数据库备份")
    @PostMapping("/restore")
    @RequirePerm({"system:backup"})
    public ApiBaseResponse<Map<String, Object>> restoreDatabase(@RequestParam String ossKey) {
        boolean success = backupService.restoreDatabase(ossKey);
        Map<String, Object> result = new HashMap<>();
        result.put("success", success);
        result.put("message", success ? "数据库恢复成功" : "数据库恢复失败");
        return ApiBaseResponse.success(result);
    }
    
    @Operation(summary = "删除备份文件")
    @DeleteMapping("/delete")
    @RequirePerm({"system:backup"})
    public ApiBaseResponse<Map<String, Object>> deleteBackupFile(@RequestParam String ossKey) {
        boolean success = backupService.deleteBackupFile(ossKey);
        Map<String, Object> result = new HashMap<>();
        result.put("success", success);
        result.put("message", success ? "备份文件删除成功" : "备份文件删除失败");
        return ApiBaseResponse.success(result);
    }
    
    @Operation(summary = "清理过期备份")
    @DeleteMapping("/cleanup")
    @RequirePerm({"system:backup"})
    public ApiBaseResponse<Map<String, Object>> cleanupOldBackups(@RequestParam(defaultValue = "30") int retentionDays) {
        try {
            backupService.cleanupOldBackups(retentionDays);
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "过期备份清理成功");
            return ApiBaseResponse.success(result);
        } catch (Exception e) {
            return ApiBaseResponse.error(500, "清理过期备份失败: " + e.getMessage());
        }
    }
    
    private String getBackupType(String ossKey) {
        if (ossKey.contains("/database/")) {
            return "数据库备份";
        } else if (ossKey.contains("/files/")) {
            return "文件备份";
        } else if (ossKey.contains("/full/")) {
            return "完整备份";
        } else {
            return "未知类型";
        }
    }
    
    private String extractFileName(String ossKey) {
        int lastSlash = ossKey.lastIndexOf('/');
        return lastSlash >= 0 ? ossKey.substring(lastSlash + 1) : ossKey;
    }
}